<?php

/**
 * This is the model class for table "sd.photos".
 *
 * The followings are the available columns in table 'sd.photos':
 * @property string $id
 * @property string $target_id
 * @property string $target_type
 * @property string $path
 * @property string $file
 * @property string $title
 * @property string $description
 * @property integer $is_main
 * @property string $upload_user
 * @property string $upload_time
 * @property string $original_url
 *
 * The followings are the available model relations:
 * @property Users $uploadUser
 */
class Photos extends CBaseActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'sd.photos';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('target_type, path', 'required'),
			array('is_main', 'numerical', 'integerOnly'=>true),
			array('target_id, upload_user, upload_time', 'length', 'max'=>10),
			array('target_type', 'length', 'max'=>30),
			array('path, file, original_url', 'length', 'max'=>255),
			array('title, description', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, target_id, target_type, path, file, title, description, is_main, upload_user, upload_time, original_url', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'uploadUser' => array(self::BELONGS_TO, 'Users', 'upload_user'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'target_id' => 'Target',
			'target_type' => 'Target Type',
			'path' => 'Path',
			'file' => 'File',
			'title' => 'Title',
			'description' => 'Description',
			'is_main' => 'Is Main',
			'upload_user' => 'Upload User',
			'upload_time' => 'Upload Time',
			'original_url' => 'Original Url',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('target_id',$this->target_id,true);
		$criteria->compare('target_type',$this->target_type,true);
		$criteria->compare('path',$this->path,true);
		$criteria->compare('file',$this->file,true);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('is_main',$this->is_main);
		$criteria->compare('upload_user',$this->upload_user,true);
		$criteria->compare('upload_time',$this->upload_time,true);
		$criteria->compare('original_url',$this->original_url,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Photos the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function selectMainByRowset(&$oRowset, $key = 'id')
	{
        if(empty($oRowset))
            return array();

		$ids = array();
		$type = '';

		foreach($oRowset as $oRow)
		{
			$ids[] = $oRow->$key;
			$type = $oRow->getTableName();
		}

		$oCriteria = $this->getDbCriteria();
		$oCriteria->addInCondition('target_id', $ids);
		$oCriteria->addColumnCondition(array('target_type' => $type));
		$oCriteria->order = 'is_main ASC';
//		$oCriteria->group = 'target_id';

		$oPhotos = $this->findAll($oCriteria);

		$aPhotos = array();
		foreach($oPhotos as $oPhoto)
		{
			$aPhotos[$oPhoto->target_id] = $oPhoto;
		}

//        print_r($aPhotos); exit;

		foreach($oRowset as $i => $oRow)
		{
			if(isset($aPhotos[$oRow->$key]))
				$oRowset[$i]->setPhoto($aPhotos[$oRow->$key]);
		}

		return $oPhotos;
	}

	public function selectByRow(&$oRow, $key = 'id')
	{
		if(!$oRow || empty($oRow))
			return false;

		$ids = array();
		$ids[] = $oRow->$key;
		$type = $oRow->getTableName();

		$oCriteria = $this->getDbCriteria();
		$oCriteria->addInCondition('target_id', $ids);
		$oCriteria->addColumnCondition(array('target_type' => $type));
		$oCriteria->order = 'is_main DESC';

		$oPhotos = $this->findAll($oCriteria);

		$oRow->setPhotos($oPhotos);

		return $oPhotos;
	}

	public function selectAllByRow(&$oTargetRow, $key = 'id')
	{
		if(!$oTargetRow)
			return $oTargetRow;

		if($oTargetRow->$key < 1)
			return $oTargetRow;

		$type = $oTargetRow->getTableName();

		$ids = array();
		$ids[] = $oTargetRow->$key;

		$oCriteria = $this->getDbCriteria();
		$oCriteria->addInCondition('target_id', $ids);
		$oCriteria->addColumnCondition(array('target_type' => $type));

		$oPhotos = $this->findAll($oCriteria);

		$oTargetRow->setPhotos($oPhotos);

		return $oPhotos;
	}

	public function saveByTarget(CBaseActiveRecord $oTargetRow, $data)
	{
		if(empty($data['photos']))
			return false;

		$mainPhoto = 0;
		if(!empty($data['main_photo']) && $data['main_photo'] > 0)
			$mainPhoto = $data['main_photo'];

		foreach($data['photos'] as $i => $id)
		{
			$oRow = new Photos();
			$oRow = $oRow->findByPk($id);

			if($oRow)
			{
				if(!empty($oTargetRow))
					if(!empty($oTargetRow->parent_id) && $oTargetRow->parent_id > 0)
						$oRow->target_id = $oTargetRow->parent_id;
					else
						$oRow->target_id = $oTargetRow->getPrimaryKey();

				if($oTargetRow && $oTargetRow->tableName())
					$oRow->target_type = $oTargetRow->getTableName();

				if($mainPhoto > 0 && $id == $mainPhoto)
					$oRow->is_main = 1;
				else if($mainPhoto == 0 && $i == 0)
					$oRow->is_main = 1;
				else
					$oRow->is_main = 0;

				if(!empty($data['photos_title'][$i]))
					$oRow->title = $data['photos_title'][$i];
				else
					$oRow->title = '';

				$oRow->save();

				unset($data['photos'][$i]);
			}
		}

		return true;
	}
}
